package com.jeasonzhao.commons.logger;

import java.io.File;
import java.util.Date;

public class FileLogListener extends MessageBasedLogListener
{
    private java.io.FileWriter m_logFileWritter = null;
    public FileLogListener(String strFolder,String strPrefix)
    {
        init(null == strFolder || strFolder.trim().length() < 1 ? "./" : strFolder.trim() + "/"
             ,null == strPrefix || strPrefix.trim().length() < 1 ? "default_system" : strPrefix.trim());
    }

    public void init(String strLogPath,String strPrefix)
    {
        java.io.File dir = new File(strLogPath);
        if(dir.exists() == false)
        {
            if(dir.mkdirs() == false
               && strLogPath.equalsIgnoreCase("./logs") == false)
            {
                strLogPath = "./logs";
                dir = new File(strLogPath);
                if(dir.exists() == false)
                {
                    if(dir.mkdirs() == false)
                    {
                        ConsoleLogger.getInstance().fatal("Could not create folder to save log files.");
                    }
                }
            }
        }
        String strFileName = strLogPath + "/" + strPrefix
            + (new java.text.SimpleDateFormat("yyyyMMdd").format(new Date()));
        String strLastName = null;
        int nFileIndex = 0;
        while(nFileIndex < 1000)
        {
            try
            {
                String st = strFileName;
                if(nFileIndex > 0)
                {
                    String xx = "" + nFileIndex;
                    while(xx.length() < 4)
                    {
                        xx = "0" + xx;
                    }
                    st += "_" + xx;
                }
                st += ".log";
                nFileIndex++;
                File logFile = new File(st);
                if(logFile.exists())
                {
                    continue;
                }
                java.io.File file = new File(strFileName + ".log");
                if(file.exists())
                {
                    if(file.renameTo(logFile) == false)
                    {
                        ConsoleLogger.getInstance().fatal("Could not rename file from " + file.getAbsolutePath()
                            + " to " + logFile.getAbsolutePath());
                    }
                }
                strLastName = strFileName + ".log";
                file = new File(strLastName);
                ConsoleLogger.getInstance().system("Current log file: " + file.getAbsolutePath());
                m_logFileWritter = new java.io.FileWriter(strLastName,false);
                break;
            }
            catch(Exception excep)
            {
                continue;
            }
        }
    }

    protected void writeToFile(String strMessage)
    {
        if(null == strMessage)
        {
            return;
        }
        synchronized(this)
        {
            try
            {
                m_logFileWritter.write(strMessage + "\n");
                m_logFileWritter.flush();
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }

    public synchronized void close()
    {
        if(null != m_logFileWritter)
        {
            try
            {
                m_logFileWritter.close();
            }
            catch(Exception ex)
            {
            	ex.printStackTrace();
            }
        }
    }

    public void log(LogLevel logLevel,String strMessage,Throwable excep)
    {
        writeToFile(formatMessage(logLevel,null,strMessage,excep));
    }
}
